/*表示部-UI関連はここに書く*/

var gUser = null; 			//ログインユーザー
var gTweetData = null;		//ツイートデータ
var gMapDisplayFlag = false;
var gMap;

function initializeUI(){
	initializeUser();	
}

function initializeUser(){
	getLoginedUser(function(data, dataType){
		gUser = data;
		//tweetタブの初期化
		initializeTweets();
		//mapタブの初期化
		//地図を表示してdisplay:noneにするとバグるらしい
		//requestPosition(initializeMap);
	})
}

/* 始めて地図を表示する場合だけrequestPositionを呼ぶ */
function renderMap(){
	if(gMapDisplayFlag){
		requestPosition(setPresentPosition);
	} else {
		requestPosition(initializeMap);
	}
}

/*
 * tweetタブの初期化
 */
function initializeTweets(){
	//$("#tweet").empty();
	var statusId = (gTweetData == null) ? 0 : gTweetData[gTweetData.length - 1]['Status']['id'];//一番最後のIDを付加
	var count = 10;
	
	$("#tweet").append('<div id="tweet-loader" align="center"><img src="'+ WEB_ROOT + 'img/ajax-loader.gif"　align="middle"><div align="center">');
	getStatusesBySchoolId(function(data, dataType){
		$("#tweet-loader").remove();
		gTweetData = (gTweetData == null) ? data : gTweetData.concat(data);//nullでないならtweetを結合
		console.log(data);
		var list = '';
		for(index in data){

			var actionUrl;
			//お気に入り登録or削除
			var imgUrl;
			var inner;
			var className = '';
			var favoriteList = '';
			if(data[index]['Favorite'] == null) {
				actionUrl = WEB_ROOT + 'favorites/add/' + gUser['User']['id'] + '/' + data[index]['Status']['id'] + '/'
				imgUrl = WEB_ROOT + 'img/star--plus.png';
				inner = 'お気に入りに追加';
				className = 'tweet_unit';
			} else {
				actionUrl = WEB_ROOT + 'favorites/del/' + data[index]['Favorite']['id'] + '/';
				imgUrl = WEB_ROOT + 'img/star--minus.png';
				inner = 'お気に入りから削除';
				className = 'tweet_unit_favorite';
			}
			favoriteList += '<div class="star"><a href="' + actionUrl + '" data-ajax="false">';
			favoriteList += '<img src="' + imgUrl + '" />' + inner + '</a></div>';
			
			list += '<div class="' + className + '" data-theme="a" data-content-theme="a">';
			list += '<img src="' +data[index]['TwitterUser']['profile_image_url']+ '"/>';
			list += '<div class="right_tweet_area">';
			list += '<div class="username">' + data[index]['TwitterUser']['name'] + '</div>';			
			list += '<div class="tweet">' +data[index]['Status']['text']+ '</div>';
			list += '<div class="buttom_line"><div class="address"><a href="#map-page" onclick="dispAroundTweet('+ index + ')">' +data[index]['Location']['Address']['name']+ '</a>より</div>';
			if(gUser['User']['id'] != data[index]['User']['id']){
				list += favoriteList;
			}
			list += '</div><div style="clear:both;"></div></div>';
			list += '</div>';
		}
		if(data.length != 0){
			list += '<div id="more_unit" class="tweet_unit" data-theme="a" data-content-theme="a">';
			list += '<div class="more">もっと読み込む</div></div>'
		}
		$("#tweet").append(list);
		$("#more_unit").click(function(){
			$("#more_unit").remove();
			initializeTweets();
		});
		/*
		$("#tweet").hide();
		$("#tweet").slideDown("slow");*/
	},
	null,
	gUser['Campus']['school_id'],
	statusId,
	count);
}


/*
 * Tweetの住所をクリックするとMapタブにその周辺地図を表示
 */
function dispAroundTweet(index) {
	console.log(index);
	console.log(gTweetData[index]);
	var lat = gTweetData[index]['Location']['lat'];
	var lng = gTweetData[index]['Location']['lng'];
	var latlng = new google.maps.LatLng(lat, lng);
	//$("#tweet").hide();
	//$("#map").show();
	if(gMapDisplayFlag){
		gMap.setCenter(latlng);
		getCenter();
		console.log('hoge');
	} else {
		initializeMapFromAddress(latlng);
	}
}
/*
 * Tweetの住所からMapTabが表示されたときの初期化
 */
function initializeMapFromAddress(latlng){
	var opts = {
		zoom:17,
		center:latlng,
		mapTypeId:google.maps.MapTypeId.ROADMAP
	};
	var mC = document.getElementById("map_canvas");
	gMap = new google.maps.Map(mC,opts);
	console.log('initializeMapFromAddress');
	gMapDisplayFlag = true;
	//setTimeout('dummy()', 3000);
	//getCenter();
	// 地図をドラッグしたら、中央の座標を取得して表示、これから活用予定
	//google.maps.event.addListener(gMap, 'dragend', getCenter);
	google.maps.event.addListener(gMap, 'tilesloaded', getCenter);
}
/*
 * MapTabの初期化
 */
function initializeMap(position){
	var lat = position.coords.latitude;
	var lng = position.coords.longitude;
	// まずは自分が中心の地図を表示
    var latlng = new google.maps.LatLng(lat,lng);
	var opts = {
		zoom:17,
		center:latlng,
		mapTypeId:google.maps.MapTypeId.ROADMAP
	};
	var mC = document.getElementById("map_canvas");
	gMap = new google.maps.Map(mC,opts);
	console.log ('initializeMap!!');
	gMapDisplayFlag = true;
	//setTimeout('dummy()', 3000);
	//getCenter();
	// 地図をドラッグしたら、中央の座標を取得して表示、これから活用予定
	//google.maps.event.addListener(gMap, 'dragend', getCenter);
	google.maps.event.addListener(gMap, 'tilesloaded', getCenter);
	
}
/* ダミー関数 */
function dummy(){
	console.log('called dummy');
}
/*
 * Mapタブの位置更新
 */
function setPresentPosition(position){
	var lat = position.coords.latitude;
	var lng = position.coords.longitude;
    var latlng = new google.maps.LatLng(lat,lng);
	gMap.setCenter(latlng);
	getCenter();
}
/*
 * Aroundの初期化
 */
function initializeAround(data){
	$("#tweet_list").empty();
	var list = '';
	for(index in data){
			var actionUrl;
			//お気に入り登録or削除
			var imgUrl;
			var inner;
			var className = '';
			var favoriteList = '';
			if(data[index]['Favorite'] == null) {
				actionUrl = WEB_ROOT + 'favorites/add/' + gUser['User']['id'] + '/' + data[index]['Status']['id'] + '/'
				imgUrl = WEB_ROOT + 'img/star--plus.png';
				inner = 'お気に入りに追加';
				className = 'tweet_unit';
			} else {
				actionUrl = WEB_ROOT + 'favorites/del/' + data[index]['Favorite']['id'] + '/';
				imgUrl = WEB_ROOT + 'img/star--minus.png';
				inner = 'お気に入りから削除';
				className = 'tweet_unit_favorite';
			}
			favoriteList += '<div class="star"><a href="' + actionUrl + '" data-ajax="false">';
			favoriteList += '<img src="' + imgUrl + '" />' + inner + '</a></div>';
			
			list += '<div class="' + className + '" data-theme="a" data-content-theme="a">';
			list += '<img src="' +data[index]['TwitterUser']['profile_image_url']+ '"/>';
			list += '<div class="right_tweet_area">';
			list += '<div class="username">' + data[index]['TwitterUser']['name'] + '</div>';			
			list += '<div class="tweet">' +data[index]['Status']['text']+ '</div>';
			list += '<div class="buttom_line"><div class="address"><a href="#map-page" onclick="dispAroundTweet('+ index + ')">' +data[index]['Location']['Address']['name']+ '</a>より</div>';
			if(gUser['User']['id'] != data[index]['User']['id']){
				list += favoriteList;
			}
			list += '</div><div style="clear:both;"></div></div>';
			list += '</div>';
		}
	$("#tweet_list").append(list);
}


function initializeSearchResult(word, category_id){
	searchStatuses(
		function(data, dataType){
			console.log(data);
			list = "";
			$("#search-result").empty();
			if(data['Error']){
				return false;
			}
			for(index in data){
				list += '<div class="tweet_unit" data-theme="a" data-content-theme="a">';
				list += '<img src="' +data[index]['TwitterUser']['profile_image_url']+ '"/>';
				list += '<div class="right_tweet_area">';
				list += '<div class="username">' + data[index]['TwitterUser']['name'] + '</div>';			
				list += '<div class="tweet">' +data[index]['Status']['text']+ '</div>';
				list += '<div class="buttom_line"><div class="address"><a href="#" onclick="dispAroundTweet('+ index + ')">' +data[index]['Location']['Address']['name']+ '</a>より</div>';
				if(gUser['User']['id'] != data[index]['User']['id']){
					var actionUrl;	//お気に入り登録or削除
					var imgUrl;
					var inner;
					if(data[index]['Favorite'] == null){
						actionUrl = WEB_ROOT + 'favorites/add/' + gUser['User']['id'] + '/' + data[index]['Status']['id'] + '/'
						imgUrl = WEB_ROOT + 'img/star--plus.png';
						inner = 'お気に入りに追加';
					}else{
						actionUrl = WEB_ROOT + 'favorites/del/' + data[index]['Favorite']['id'] + '/';
						imgUrl = WEB_ROOT + 'img/star--minus.png';
						inner = 'お気に入りから削除';
					}
					list += '<div class="star"><a href="' + actionUrl + '" data-ajax="false">';
					list += '<img src="' + imgUrl + '" />' + inner + '</a></div>';
				}
			list += '</div><div style="clear:both;"></div></div>';
			list += '</div>';
		}
			$("#search-result").append(list);
		},
		function(){
			
		},
		word,
		category_id
		);
}
$(function(){
	initializeUI(); //UIの初期化
	/*$('#map-page').live('pageshow', function(){
		requestPosition(initializeMap);
	});*/
	$("#map-btn").click(function(){
		requestPosition(renderMap);
	});
	$("#search-form").submit(function(){
		var word = $("#statuses-search-box").val();
		var category_id = $("#statuses-search-select").val();
		$("#search-result").empty();
		$("#search-result").append('<img src='+ WEB_ROOT + 'img/ajax-loader.gif>');
		initializeSearchResult(word, category_id);
		return false;
	});
	
});